package com.sky.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

@Data
@Component
@Slf4j
@ConfigurationProperties(prefix = "sky.local")
public class LocalFileUtil {

    private String basePath;
    private String baseUrl;

    /**
     * 文件上传
     * @param bytes
     * @param originalFilename
     * @return
     */
    public String upload(byte[] bytes, String originalFilename) {
        // 生成新的文件名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID().toString() + extension;

        // 创建目标目录
        File directory = new File(basePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 创建文件并写入数据
        String filePath = basePath + File.separator + objectName;
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(bytes);
        } catch (IOException e) {
            log.error("文件上传失败：{}", e.getMessage());
            throw new RuntimeException(e);
        }

        // 返回文件访问路径
        return baseUrl + "/" + objectName;
    }
} 